// collectList.js
import { getCloudImage } from '../../utils/images';

const BANNER_ID = 'cloud://dp-6gydzcp27ac11774.6470-dp-6gydzcp27ac11774-1325695033/默认图片/bg3.webp';

Page({
  data: {
    list: [],
    loading: true,
    currentType: '', // 保存当前页面类型
    bgImage:''
  },

  async onLoad(options) {
    this.setData({ currentType: options.type });
    this.loadData();
    // 获取背景图片
    const url = await getCloudImage(BANNER_ID);
    this.setData({ bgImage: url });
  },

  onShow() {
    // 每次页面显示时刷新数据
    this.loadData();
  },

  onPullDownRefresh() {
    // 下拉刷新处理
    this.loadData(() => {
      wx.stopPullDownRefresh();
    });
  },

  async loadData(callback) {
    try {
      this.setData({ loading: true });
      
      const db = wx.cloud.database();
      const { data } = await db.collection('CollectList')
        .where({ type: this.data.currentType })
        .orderBy('createTime', 'desc')
        .get();

      this.setData({
        list: data.map(item => ({
          ...item,
          createTime: this.formatTime(item.createTime)
        })),
        loading: false
      });
    } catch (err) {
      console.error('数据加载失败', err);
      wx.showToast({ title: '加载失败', icon: 'none' });
      this.setData({ loading: false });
    } finally {
      callback && callback();
    }
  },

  formatTime(time) {
    const date = new Date(time)
    return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`
  },

   // 跳转到详情页面
   goToDetail(e) {
    const { id, type } = e.currentTarget.dataset;
    if (type === 'map') {
      wx.navigateTo({
        url: `/pages/mapInfo/mapInfo?id=${id}`
      });
    } else if(type === 'food') {
      wx.navigateTo({
        url: `/pages/foodDetail/foodDetail?id=${id}`,
      })
    }else if(type === 'story'){
      wx.navigateTo({
        url: `/pages/stroyDetail/stroyDetail?id=${id}`,
      })
    }
  }
})